<?php

namespace App\Http\Controllers\Api;

use App\Http\Model\User;
use App\Model\ActiveCertify;
use App\Model\AdminLog;
use App\Model\AudioApi;
use App\Model\FinanceBeforeKkWealth;
use App\Model\FinanceKkStream;
use App\Model\FinanceWallet;
use App\Model\Number;
use App\Model\OperationLogs;
use App\Model\Room;
use App\Model\RoomRole;
use App\Model\RoomWealthStream;
use App\Model\Support;
use App\Model\TrendsContent;
use App\Model\UserActiveStatistics;
use App\Model\UserBlockLog;
use App\Model\UserBlockRule;
use App\Model\UserVerify;
use App\Model\ChatLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Model\ApiUser;
use Illuminate\Support\Facades\Redis;
class NumberController extends BaseController
{
    protected $model;
    protected $apiUserModel;
    protected $audioApiModel;
    protected $chatLogModel;
    protected $roomRole;

    public function __construct(Request $request, Number $number, ChatLog $chatLog, RoomRole $roomRole)
    {
        parent::__construct($request);
        $this->model = $number;
        $this->audioApiModel = new AudioApi();
        $this->chatLogModel = new ChatLog();
        $this->roomRole = $roomRole;
        $this->apiUserModel = new ApiUser();
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $numbers = $this->model->getList($request);
        return $this->toJson(self::SUCCESS, $numbers);
    }

    /**
     * 设置默认用户头像
     * @param Request $request
     * @param $number_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDefaultHeadImg(Request $request, $number_id)
    {
        $res = curl_request(config('kkaudio.kkaudio_api') . '/inner/user/edit_user', [
            'user_id' => $number_id,
            'images' => config('kkaudio.oss_url') . Number::DEFAULT_HEAD_IMG,
        ], 'json', 'POST');
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::NUMBER, '恢复房间默认头像', $number_id);
            return $this->toJson(self::SUCCESS, ['img' => config('kkaudio.oss_url') . Number::DEFAULT_HEAD_IMG]);
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    /**
     * 修改用户昵称
     * @param Request $request
     * @param $number_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setNickname(Request $request, $number_id)
    {
        $validator = Validator::make($request->all(), [
            'nickname' => 'bail|required|string'
        ], [
            'nickname.required' => '昵称不可为空'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }

        $res = curl_request(config('kkaudio.kkaudio_api') . '/inner/user/edit_user', [
            'user_id' => $number_id,
            'nickname' => $request->input('nickname'),
        ], 'json', 'POST');
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::NUMBER, '设置用户昵称', $number_id);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }
    /**
     * 修改用户性别
     * @param Request $request
     * @param $number_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setGender(Request $request, $number_id)
    {

        $validator = Validator::make($request->all(), [
            'gender' => 'bail|required|int'
        ], [
            'gender.required' => '性别不可为空'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }

        $res = curl_request(config('kkaudio.kkaudio_api') . '/inner/user/edit_user', [
            'user_id' => $number_id,
            'gender' => $request->input('gender'),
        ], 'json', 'POST');
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::NUMBER, '设置用户性别', $number_id);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    /**
     * 用户钱包
     * @param $user_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function finance($user_id)
    {
        return $this->toJson(self::SUCCESS, FinanceWallet::where(['user_id' => $user_id])->first());
    }

    /**
     * 用户流水
     * @param Request $request
     * @param FinanceKkStream $stream
     * @return \Illuminate\Http\JsonResponse
     */
    public function charm(Request $request, FinanceKkStream $stream)
    {
        return $this->toJson(self::SUCCESS, $stream->getCharm($request));
    }

    /**
     * 封号/解封
     * @param Request $request
     * @param int $number_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function handleForbid(Request $request, int $number_id)
    {
        $validator = Validator::make($request->all(), [
            'forbid_type' => 'bail|required|integer',
            Rule::in(1, 2),
            'operate_type' => 'bail|required|integer',
            Rule::in(0, 1),
            'delete_trend' => 'bail|required',
            'user_id' => 'bail|required|integer|exists:api.user'
        ], [
            'forbid_type.required' => '操作类型不可为空',
            'forbid_type.integer' => '操作类型只能事整数',
            'operate_type.required' => '设备类型不可为空',
            'operate_type.integer' => '设备类型只能是整数',
            'user_id.required' => '被操作用户不可为空',
            'user_id.exists' => '被操作用户不存在'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->first());
        }

        $number = $this->model->find($number_id);
        $uuid = $number->uuid;
        $delete_trend = $request->input('delete_trend', false);

        $url = getKkaudioApiUrl() . '/inner/user/forbid_user';
        $operation_id = $request->input('report_user_id');
        $time_out = time();
        $this->model->getForbidList();
        if (isset($this->model->forbidUser[$request->input('user_id')])) {
            if ($this->model->forbidUser[$request->input('user_id')] > 0) {
                $time_out = $this->model->forbidUser[$request->input('user_id')] + $request->input('block_time');
            }
        } else {
            $time_out += $request->input('block_time');
        }

        // 永久
        if ($request->input('block_time') == 0) {
            $time_out = 0;
        }
        $is_limit_ip = in_array($request->input('reason_id'), array(31, 32)) ? 1 : 0;
        $res = curl_request($url, ['user_id' => $operation_id, 'timeout' => $time_out, 'is_limit_ip' => $is_limit_ip], 'json', 'POST');
        if ($res['code'] == 0) {
            $allData = $request->all();
            if (empty($allData['operate_info']))
                $allData['operate_info'] = '账号封禁';
            $data = array_merge($allData, ['operate_time' => $_SERVER['REQUEST_TIME'], 'block_time' => $time_out, 'uuid' => $uuid, 'operation_id' => $this->user->id]);
            $data['delete_trend'] = 0;
            if ($delete_trend === true) {
                $data['delete_trend'] = 1;
            }
            if (empty($data['reason_img'])) {
                $data['reason_img'] = '';
            } else {
                $data['reason_img'] = implode(',', $data['reason_img']);
            }
            $UserBlockLogModel = new UserBlockLog();
            $UserBlockLog = $UserBlockLogModel->createData($data);
            if ($UserBlockLog['code'] !== 0) {
                return $this->toJson(self::ERROR, $UserBlockLog);
            }
            OperationLogs::createData($request, OperationLogs::NUMBER, "封用户", $uuid);
            return $this->toJson(self::SUCCESS, $UserBlockLog);
        }
        return $this->toJson(self::ERROR);
    }

    public function deblockingUser(Request $request)
    {
        $url = getKkaudioApiUrl() . '/inner/user/remove_forbid_user';
        $user = $this->user;
        $this->model->getForbidList();
        $res = curl_request($url, ['user_id' => $request->input('user_id'), 'timeout' => strtotime($this->model->forbidUser[$request->input('user_id')] + $request->input('block_time'))], 'json', 'POST');
        if ($res['code'] == 0) {
            $allData = $request->all();
            if (empty($allData['operate_info']))
                $allData['operate_info'] = '账号解封';
            $data = array_merge($allData, ['operation_id' => intval($user['id']), 'operate_time' => $_SERVER['REQUEST_TIME'], 'block_time' => 0, 'uuid' => $request->input('uuid'), 'reason_id' => 0, 'delete_trend' => 0]);
            $UserBlockLogModel = new UserBlockLog();
            $userBlockLog = $UserBlockLogModel->createData($data);
            if ($userBlockLog['code'] !== 0) {
                return $this->toJson(self::ERROR, $userBlockLog, $userBlockLog['msg']);
            }
            $data['users'] = $user;
            OperationLogs::createData($request, OperationLogs::NUMBER, "解封用户", $request->input('uuid'));
            return $this->toJson(self::SUCCESS, $data);
        }
        return $this->toJson(self::ERROR);
    }

    /**
     * 设置金币比例
     * @param Request $request
     * @param int $wallet_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setCharmToKk(Request $request, int $wallet_id)
    {
        $charm_to_kk = $request->input('charm_to_kk', 5);
        $data['wallet_id'] = $wallet_id;
        $data['charm_to_kk'] = $charm_to_kk;
        $finance = new FinanceWallet();
        $res = $finance->updateData($data);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, $res);
        }
        OperationLogs::createData($request, OperationLogs::NUMBER, '设置金币兑换比例', $wallet_id);
        return $this->toJson();
    }

    /**
     * 注册统计
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function registerStatistics(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);

        return $this->toJson(self::SUCCESS, $this->model->getRegisterStatistics($limit, $page));
    }

    /**
     * 正常用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllNumbers(Request $request)
    {
        $uuid = $request->input('uuid');
        $is_batch = $request->input('is_batch') ?? 0;
        if (!$uuid)
            return $this->toJson(self::SUCCESS);
        if (!empty($is_batch)) {
            $uuids = explode(',', $uuid);
            $query = $this->model->with(['financeWallet:user_id,kk_balance']);
            if ($uuids)
                $query = $query->whereIn('uuid', $uuids);
        } else {
            $query = $this->model->with(['financeWallet:user_id,kk_balance']);
            if ($uuid)
                $query = $query->where('uuid', 'like', "{$uuid}%");
        }
        return $this->toJson(self::SUCCESS, $query->where(['is_block' => 0])->where('user_id', '>', 200)->get(['uuid', 'user_id', 'nickname']));
    }

    public function userBlockLogs($user_id)
    {
        $data = UserBlockLog::with(['userBlockRule', 'users:id,name'])->orderBy('id', 'DESC')->where(['user_id' => $user_id])->get();
        foreach ($data as $key => $value) {
            $data[$key]->reason_img = explode(',', $value->reason_img) ?? [];
        }
        return $this->toJson(self::SUCCESS, $data);
    }

    /**
     * 根据 pid 获取封号规则分类
     * @param Request $request
     * @param UserBlockRule $userBlockRule
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserBlockRules(Request $request, UserBlockRule $userBlockRule)
    {
        $validator = Validator::make($request->all(), [
            'pid' => 'bail|required|integer'
        ], [
            'pid.required' => 'PID不可为空'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::SUCCESS, $validator->errors()->all()[0]);
        }
        return $this->toJson(self::SUCCESS, $userBlockRule->getRule(['pid' => $request->input('pid')]));
    }

    /**
     * 封号时长
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserBlockDuration()
    {
        return $this->toJson(self::SUCCESS, UserBlockLog::FORBID_DURATION);
    }

    /**
     * 获取封号列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function getForbidUserList()
    {
        $this->model->getForbidList();
        $forbid = $this->model->forbidUser;
        return $this->toJson(self::SUCCESS, $forbid);
    }

    /**
     * 设置 UUID
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setUUID(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'old_uuid' => 'bail|required|exists:api.user,uuid',
            'uuid' => 'bail|required',
            'end_date' => 'nullable',
        ], [
            'old_uuid.required' => 'old_uuid必须',
            'old_uuid.exists' => '被操作的用户不存在',
            'uuid.required' => 'uuid必须'
        ]);

        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }

        $params = $validator->validated();
        // 判断该UUID是否已被设置
        if ($this->model->uuidIsSet($params['uuid'])) {
            return $this->toJson(self::ERROR, [], '该UUID已被使用');
        }

        //$res = $this->model->setUUID($id, $request->input('uuid'));
        $res = $this->model->setUUIDV2($params['old_uuid'], $params['uuid'], $params['end_date'] ?? 0, $this->user->id, $this->user->name);
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::NUMBER, "更改UUID", $request->input('old_uuid'));
            return $this->toJson(self::SUCCESS);
        }

        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    /**
     * 设置靓号
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setGoodMobileNumber(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'liang' => ['bail', 'required', Rule::in(0, 1)]
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }
        $res = $this->model->setGoodMobileNumber($id, $request->input('liang'));
        if ($res['code'] == 0) {
            $log_prefix = '设置靓号';
            if ($request->input('liang') == 0)
                $log_prefix = '取消靓号';
            OperationLogs::createData($request, OperationLogs::NUMBER, $log_prefix, $id);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    /**
     * 设置超管
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setSuper(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'super' => ['bail', 'required', Rule::in(0, 1)]
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }
        if ($this->model->setSuper($id, $request->input('super'))) {
            $log_prefix = '设置超管';
            if ($request->input('super') == 0)
                $log_prefix = '取消超管';
            OperationLogs::createData($request, OperationLogs::NUMBER, $log_prefix, $id);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR);
    }

    /**
     * 设置官方
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setOfficial(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'official' => ['bail', 'required', Rule::in(0, 1)]
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }
        if ($this->model->setOfficial($id, $request->input('official'))) {
            $log_prefix = '设置官方';
            if ($request->input('official') == 0)
                $log_prefix = '取消官方';
            OperationLogs::createData($request, OperationLogs::NUMBER, $log_prefix, $id);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR);
    }

    /**
     * 设置巡房
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setWaiter(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'waiter' => ['bail', 'required', Rule::in(0, 1)]
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }
        if ($this->model->setWaiter($id, $request->input('waiter'))) {
            $log_prefix = '设置巡房';
            if ($request->input('waiter') == 0)
                $log_prefix = '取消巡房';
            OperationLogs::createData($request, OperationLogs::NUMBER, $log_prefix, $id);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR);
    }

    /**
     * 用户统计
     * @param Request $request
     * @param UserActiveStatistics $userActiveStatistics
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserActiveStatisticsList(Request $request, UserActiveStatistics $userActiveStatistics)
    {
        return $this->toJson(self::SUCCESS, $userActiveStatistics->getList($request));
    }

    /**
     * 获取用户认证信息
     * @param $number_id
     * @param UserVerify $userVerify
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserActiveCertifyInfo($number_id, UserVerify $userVerify)
    {
        return $this->toJson(self::SUCCESS, $userVerify->getActiveCertifyInfoByUserId($number_id));
    }

    /**
     * 封号列表
     * @param Request $request
     * @param UserBlockLog $userBlockLog
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserByForbidList(Request $request, UserBlockLog $userBlockLog, Number $number)
    {
        $number->getForbidList();
        $user_id = array_keys($number->forbidUser);
        if (empty($user_id))
            return $this->toJson(self::SUCCESS);
        $forbidUsers = $userBlockLog->getList($request, $user_id);
        return $this->toJson(self::SUCCESS, $forbidUsers);
    }

    /**
     * 创建身份认证信息
     * @param Request $request
     * @param ActiveCertify $activeCertify
     * @return \Illuminate\Http\JsonResponse
     */
    public function createActiveCertify(Request $request, ActiveCertify $activeCertify)
    {
        $validator = Validator::make($request->all(), [
            'type' => ['bail', 'required', Rule::in(1, 2, 3, 4, 5)],
            'card_id' => 'bail|required'
        ], [
            'card_id.required' => '身份证号必填'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }
        //检测用户实名次数
        $userVerify = new UserVerify();
        $authNum = $userVerify->getIdcardNum($request->input('card_id'));
        if ($authNum >= 3) {
            return $this->toJson(self::ERROR, [], '认证次数已上线');
        }

        $card_info_res = curl_request(getKkaudioApiUrl() . '/inner/user/create_user_verity', [
            'user_id' => $request->input('user_id'),
            'idcardName' => $request->input('card_name'),
            'idcard' => $request->input('card_id')
        ], 'json', 'POST');
        if ($card_info_res['code'] !== 0)
            return $this->toJson(self::ERROR, [], $card_info_res['msg']);
        $certify_res = curl_request(getKkaudioApiUrl() . '/inner/user/set_active_certify', [
            'user_id' => $request->input('user_id'),
            'active_certify' => 1
        ], 'json', 'POST');
        if ($certify_res['code'] == 0) {
            $activeCertify->createData($request);
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR, [], $certify_res['msg']);
    }

    /**
     * 获取认证详情
     * @param $user_id
     * @param ActiveCertify $activeCertify
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActiveCertifyInfo($user_id, ActiveCertify $activeCertify)
    {
        return $this->toJson(self::SUCCESS, $activeCertify->getInfo($user_id));
    }

    /*
     * 获取用户照片墙
     * @param $user_id
     */
    public function getUserPriceWall($user_id)
    {
        return $this->toJson(self::SUCCESS, $this->model->getPrice($user_id));
    }

    //删除用户照片
    public function delPriceWall(Request $request)
    {
        return $this->toJson(self::SUCCESS, $this->model->delPriceWall($request));
    }

    //用户个性签名
    public function getUserSign($user_id)
    {
        return $this->toJson(self::SUCCESS, $this->model->userSign($user_id));
    }

    //修改个签
    public function editUserSign(Request $request)
    {
        return $this->toJson(self::SUCCESS, $this->model->editUserSign($request));
    }

    //用户加V
    public function setUserV(Request $request)
    {
        return $this->toJson(self::SUCCESS, $this->model->setUserV($request));
    }

    public function setAbnormal(Request $request, $user_id, Number $number)
    {
        $state = $request->input('state');
        return $this->toJson(self::SUCCESS, $number->setAbnormal($request, $user_id, $state));
    }

    //优先邂逅列表
    public function userMeet(Request $request)
    {
        $res = curl_request(config('kkaudio.kkaudio_api') . '/inner/meet/first/list', [], 'urlencoded', 'GET');
        if ($res['code'] == 0) {
            return $this->toJson(self::SUCCESS, $res['data']);
        }
        return $this->toJson(self::ERROR);
    }

    //删除匹配
    public function delUserMeet(Request $request)
    {
        $req = $request->input();
        $data['uid'] = $req[0];
        $res = curl_request(config('kkaudio.kkaudio_api') . '/inner/meet/first/del', $data, 'urlencoded', 'GET');
        if ($res['code'] == 0) {
            return $this->toJson(self::SUCCESS, $res['data']);
        }
        return $this->toJson(self::ERROR);
    }

    //添加
    public function addUserMeet(Request $request)
    {
        $data['uid'] = $request->input('user_id');
        $res = curl_request(config('kkaudio.kkaudio_api') . '/inner/meet/first/create', $data, 'urlencoded', 'GET');
        if ($res['code'] == 0) {
            return $this->toJson(self::SUCCESS, $res['data']);
        }
        return $this->toJson(self::ERROR);
    }

    //激活二维码
    public function activateCode(Request $request)
    {
        $user_id = $request->input('user_id');
        $is_open_code = $request->input('is_open_code') == 1 ? 0 : 1;
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/edit/user_info', ['user_id' => $user_id, 'is_open_code' => $is_open_code], 'urlencoded', 'GET');
        return $this->toJson(self::SUCCESS, $res);
    }

    public function activateCodeList(Request $request)
    {
        $res = $this->model->activateCodeList($request->input());
        return $this->toJson(self::SUCCESS, $res);
    }

    public function getInviteUser(Request $request)
    {
        $res = $this->model->getInviteUser($request->input());
        return $this->toJson(self::SUCCESS, $res);
    }

    //获取用户房间流水相关
    public function getRoomWealthToUser(Request $request, Room $room, RoomWealthStream $roomWealthStream, Support $support, FinanceBeforeKkWealth $financeBeforeKkWealth)
    {
        $user_id = $request->input('user_id', 0);
        $radio = $request->input('radio', 10);//结算比例
        $user_room = $room->getUserRoom($user_id);
        $time = date('Y-m-d', time());

        foreach ($user_room as $k => &$v) {
            //获取当前房间流水
            $v['modify_radio'] = $radio;
            $v['support_radio'] = 0;
            $v['before_total'] = 0;
            $month_wealth = $roomWealthStream->getRoomMonthWealth($v['room_id'], $time);
            $month_wealth = $month_wealth['sum_total'] ?? 0;
            $support_arr = $support->getRoomSupport($v['room_id']);
            if ($support_arr) {
                $v['support_radio'] = $support->getSupportRatioValue($support_arr['support_id'], $month_wealth);
            }
            $v['month_wealth'] = floor($month_wealth * 10 * (($radio + $v['support_radio']) / 100)) / 100 ?? 0;

            $before_wealth = $financeBeforeKkWealth->getRoomBeforeWealth($v['room_id'], $time);
            $v['before_total'] = $before_wealth['sum_before_total'] / 100 ?? 0;
            $v['surplus_total'] = round($v['month_wealth'] - $v['before_total'], 2);
        }
        return $this->toJson(self::SUCCESS, $user_room);
    }

    /**获取用户每日充值限制列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getRechargeLimitList(Request $request)
    {
        $res = $this->model->getRechargeLimitList($request->input());
        return $this->toJson(self::SUCCESS, $res);
    }

    //添加/修改 限制用户每日充值数据
    public function curdRechargeLimit(Request $request)
    {
        $data['id'] = $request->input('id') ?? 0;
        $data['user_id'] = $request->input('user_id') ?? 0;
        $data['value'] = $request->input('value') ?? 0;
        $data['status'] = $request->input('status') ?? 0;
        if (empty($data['user_id']) || empty($data['value'])) {
            return $this->toJson(self::ERROR);
        }
        $admin = $this->user;
        $data['opt_id'] = $admin['id'];
        $res = $this->model->curdRechargeLimit($data);
        if ($res) {
            return $this->toJson(self::SUCCESS);
        } else {
            return $this->toJson(self::ERROR);
        }
    }

    //删除 限制每日用户充值数据
    public function delRechargeLimit(Request $request, $id)
    {
        if (empty($id)) {
            return $this->toJson(self::ERROR);
        }
        $res = $this->model->delRechargeLimit($id);
        if ($res) {
            return $this->toJson(self::SUCCESS, $res);
        } else {
            return $this->toJson(self::ERROR);
        }
    }

    /**
     * 封设备/解封设备
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function handleForbidDevice(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => 'bail|required|integer',
            Rule::in(1, 2),
        ], [
            'type.required' => '操作类型不可为空',
            'type.integer' => '操作类型只能是整数'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->first());
        }

        $allData = $request->all();
        $UserBlockLogModel = new UserBlockLog();
        $UserBlockLog = $UserBlockLogModel->handleForbidDevice($allData);

        if ($UserBlockLog['code'] !== 0) {
            return $this->toJson(self::ERROR, $UserBlockLog);
        }
        return $this->toJson(self::SUCCESS, $UserBlockLog);
    }


    /**
     * 封IP
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function handleForbidIp(Request $request)
    {
        $allData = $request->all()['user_id'];
        $UserBlockLogModel = new UserBlockLog();
        $UserBlockLog = $UserBlockLogModel->handleForbidIp(['user_id' => $allData]);
        if ($UserBlockLog['code'] !== 0) {
            return $this->toJson(self::ERROR, $UserBlockLog);
        }
        return $this->toJson(self::SUCCESS, $UserBlockLog);
    }

    /**
     * 解封IP
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function handleUnForbidIp(Request $request)
    {
        $allData = $request->all()['user_id'];
        $UserBlockLogModel = new UserBlockLog();
        $UserBlockLog = $UserBlockLogModel->handleUnForbidIp(['user_id' => $allData]);
        if ($UserBlockLog['code'] !== 0) {
            return $this->toJson(self::ERROR, $UserBlockLog);
        }
        return $this->toJson(self::SUCCESS, $UserBlockLog);
    }
    /**
     * IP禁用列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function handleDenyIpList(Request $request)
    {
        $UserBlockLogModel = new UserBlockLog();
        $UserBlockLog = $UserBlockLogModel->handleDenyIpList();
        if ($UserBlockLog['code'] !== 0) {
            return $this->toJson(self::ERROR, $UserBlockLog);
        }
        return $this->toJson(self::SUCCESS, $UserBlockLog);
    }
    /**
     * IP禁用列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function removeIpForbid(Request $request)
    {
        $allData = $request->all();
        $UserBlockLogModel = new UserBlockLog();
        $UserBlockLog = $UserBlockLogModel->remove_ip_forbid($allData);
        if ($UserBlockLog['code'] !== 0) {
            return $this->toJson(self::ERROR, $UserBlockLog);
        }
        return $this->toJson(self::SUCCESS, $UserBlockLog);
    }
    public function banned(Request $request, $id)
    {
        if (empty($id)) {
            return $this->toJson(self::ERROR);
        }
        $nowUserInfo = $this->model->getInfoByUserId($id);
        if (!$nowUserInfo) {
            return $this->toJson(self::ERROR);
        }

        $res = $this->model->banned($request->input(), $nowUserInfo['guid']);
        return $this->toJson(self::SUCCESS, $res);
    }


    public function resetDevice(Request $request, $id)
    {
        if (empty($id)) {
            return $this->toJson(self::ERROR);
        }

        $res = $this->model->resetDevice($id);
        return $this->toJson(self::SUCCESS, $res);

    }

    //用户聊天记录列表
    public function getChatLog(Request $request)
    {
        $logs = $this->chatLogModel->getChatLogList($request);
        return $this->toJson(self::SUCCESS, $logs);
    }

    //获取当日新用户聊天记录列表
    public function getNewChatLog(Request $request)
    {
        $logs = $this->chatLogModel->getNewChatLogList($request);
        return $this->toJson(self::SUCCESS, $logs);
    }

    public function account_number(Request $request, $id)
    {
        if (empty($id)) {
            return $this->toJson(self::ERROR);
        }

        $nowUserInfo = $this->model->getInfoByUserId($id);
        if (!$nowUserInfo) {
            return $this->toJson(self::ERROR);
        }

        $res = $this->model->verifyList($request->input(), $nowUserInfo['user_id']);
        return $this->toJson(self::SUCCESS, $res);
    }

    /**
     * 获取用户角色为管理员的房间列表
     * @param Request $request
     */
    public function getManageRoomList(Request $request)
    {
        $userId = $request->input('user_id', 0);
        if (!$userId) {
            return $this->toJson(self::ERROR);
        }
        $roomIds = $this->roomRole->getManageRoomIds($userId);
        $data = $this->roomRole->getRoomInfo($roomIds);

        return $this->toJson(self::SUCCESS, $data);
    }

    /**
     * 更新房间认证状态
     * @param Request $request
     */
    public function updateRoomStatus(Request $request)
    {
        $roomId = $request->input('room_id', 0);
        $user_id = $request->input('user_id', 0);
        if (empty($roomId) || empty($user_id)) {
            return $this->toJson(self::ERROR);
        }
        $res = curl_request(getKkaudioApiUrl() . '/inner/room/role/cancel', ['room_id' => $roomId, 'user_id' => $user_id], 'json', 'POST');
        OperationLogs::createData($request, OperationLogs::NUMBER, "更新房间认证状态", $user_id);
        return $this->toJson(self::SUCCESS, $res);
    }

    /**换绑手机号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeBindPhone(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required:integer',
            'phone' => 'required:string',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }
        $res = curl_request(getKkaudioApiUrl() . '/inner/user/changeBindPhone', [
            'user_id' => $request->input('user_id'),
            'phone' => $request->input('phone')
        ], 'json', 'POST');
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        $data = $res['data'];
        OperationLogs::createData($request, OperationLogs::NUMBER, "换绑手机号", $request->input('user_id'));
        return $this->toJson(self::SUCCESS, $res, $res['msg']);
    }

    /**
     * 清除认证次数
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function clearVerify(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required',
        ], [
            'user_id.required' => 'ID不能为空',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        $data = $this->model->clearVerify($request->only(['user_id']));
        if ($data['code']) {
            return $this->toJson(self::ERROR);
        }
        OperationLogs::createData($request, OperationLogs::NUMBER, "清除认证次数", $request->input("user_id"));

        return $this->toJson(self::SUCCESS);
    }

    /**
     * 清理用户实名认证
     */
    public function clearUserAll(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required',
        ], [
            'user_id.required' => 'ID不能为空',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        $data = $this->model->clearUserAll($request->only(['user_id']));
        if ($data['code']) {
            return $this->toJson(self::ERROR);
        }
        OperationLogs::createData($request, OperationLogs::NUMBER, "清理用户实名认证", $request->input("user_id"));

        return $this->toJson(self::SUCCESS);
    }

    /**
     * 清理用户银行卡绑定
     */
    public function clearUserbankAll(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_id' => 'required',
        ], [
            'user_id.required' => 'ID不能为空',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        $data = $this->model->clearUserbankAll($request->only(['user_id']));
        if ($data['code']) {
            return $this->toJson(self::ERROR);
        }
        OperationLogs::createData($request, OperationLogs::NUMBER, "清理用户银行卡绑定", $request->input("user_id"));

        return $this->toJson(self::SUCCESS);
    }

    public function getTestUser(Request $request)
    {
        $uuid = $request->input('uuid');
        $res = curl_request(getKkaudioApiUrl() . '/inner/testuser/get', [], 'json', 'GET');
        if ($res['code'] == 0) {
            if ($uuid) {
                $user = $this->model->getUserByUuid($uuid);
                if (in_array($user['user_id'], $res['data'])) {
                    $user['image'] = $this->model->getPortraitAttribute($user['portrait']);
                    return $this->toJson(self::SUCCESS, [$user]);
                } else {
                    return $this->toJson(self::SUCCESS, []);
                }
            }
            $data = $this->model->getUserByUserIDs($res['data']);
            foreach ($data as $key => $user) {
                $data[$key]['image'] = $this->model->getPortraitAttribute($user['portrait']);
            }
            return $this->toJson(self::SUCCESS, $data);
        }
        return $this->toJson(self::SUCCESS, []);
    }

    public function addTestUser(Request $request)
    {
        $user_id = $request->input('user_id');
        if (!$user_id) {
            return $this->toJson(self::PARAM_ERROR);
        }
        $res = curl_request(getKkaudioApiUrl() . '/inner/testuser/add', ['user_id' => $user_id], 'json', 'POST');
        if ($res['code'] == 0) {
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR);
    }

    public function delTestUser(Request $request)
    {
        $user_id = $request->input('user_id');
        if (!$user_id) {
            return $this->toJson(self::PARAM_ERROR);
        }
        $res = curl_request(getKkaudioApiUrl() . '/inner/testuser/del', ['user_id' => $user_id], 'json', 'POST');
        if ($res['code'] == 0) {
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR);
    }

    /**
     * 根据uuid读取用户信息
     * @param Request $request
     */
    public function getUserLoinLog(Request $request)
    {
        $uuid = $request->input('uuid', '');
        $start_time = $request->input('start_time', 0);
        $end_time = $request->input('end_time', 0);
        $page = $request->input('page', 0);
        $limit = $request->input('limit', 30);

        if (!$uuid) {
            return $this->toJson(self::PARAM_ERROR, [], 'uuid 必需');
        }

        $uinfo = $this->model->getUserByUuid($uuid);
        if (empty($uinfo)) {
            return $this->toJson(self::PARAM_ERROR, [], '未找到对应用户');
        }
        $user_id = $uinfo['user_id'];
        $result = $this->model->getUserLoginLog($user_id, $start_time, $end_time, $page, $limit);

        if ($result && $result['data']) {
            foreach ($result['data'] as $k => $val) {
                $result['data'][$k]['uuid'] = $uuid;
            }
        }

        return $this->toJson(self::SUCCESS, $result);
    }

    public function deleteUserLoinLog(Request $request)
    {
        try {
            $data = $request->all();
            $validator = Validator::make($data, [
                'id' => 'required',
            ], [
                'id.required' => 'ID不能为空',
            ]);
            if ($validator->fails()) {
                return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
            }
            DB::connection("api")->table('user_login_log')->where('id', $data['id'])->delete();
            return $this->toJson(self::SUCCESS, "ok");
        } catch (Exception $e) {
            return $this->toJson(self::ERROR, [], "删除失败！");
        }
    }


    public function updateRegDate(Request $request)
    {
        try {
            $user_id = $request->input('user_id');
            $my_reg_date = $request->input('my_reg_date');
            // $user = \App\User::where('user_id', $user_id)->first();
            // $user->create_time = $my_reg_date;
            // $user->create_timestamp = strtotime($my_reg_date);
            // $user->save();
            DB::connection("api")->table('user')->where('user_id', $user_id)->update([
                'create_time' => $my_reg_date,
                'create_timestamp' => strtotime($my_reg_date)
            ]);
            return $this->toJson(self::SUCCESS, [], '修改成功！');
        } catch (Exception $e) {
            return $this->toJson(self::ERROR, [], "修改失败！");
        }
    }


    /**
     * 根据uuid读取用户信息
     * @param Request $request
     */
    public function getUserInfo(Request $request)
    {
        $uuid = $request->input('uuid');
        if (!$uuid) {
            return $this->toJson(self::ERROR);
        }

        $uinfo = $this->model->getUserByUuid($uuid);

        $result = new \ArrayObject();
        if (!empty($uinfo)) {
            $result = $uinfo;
        }

        return $this->toJson(self::SUCCESS, $result);
    }

    //用户性别重置
    public function genderReset(Request $request)
    {
        $res = $this->apiUserModel->genderReset($request->all());
        if ($res['code'] != self::SUCCESS) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::USER, '用户性别重置');
        return $this->toJson(self::SUCCESS);
    }

    //用户验证码重置
    public function smsCodeReset(Request $request)
    {
        $res = $this->apiUserModel->smsCodeReset($request->all());
        if ($res['code'] != self::SUCCESS) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::USER, '用户验证码重置');
        return $this->toJson(self::SUCCESS);
    }

    //手机号验证码重置
    public function phonoCodeReset(Request $request)
    {
        $res = $this->apiUserModel->phonoCodeReset($request->all());
        if ($res['code'] != self::SUCCESS) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::USER, '手机号验证码重置');
        return $this->toJson(self::SUCCESS);
    }

    //设置用户头像
    public function setHeadImg(Request $request)
    {
        $res = $this->apiUserModel->setHeadImg($request->all());
        if ($res['code'] != self::SUCCESS) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::USER, '设置用户头像');
        return $this->toJson(self::SUCCESS);
    }

    //设置用户照片墙
    public function setUserPortrait(Request $request)
    {
        $res = $this->apiUserModel->setUserPortrait($request->all());
        if ($res['code'] != self::SUCCESS) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::USER, '设置用户照片墙');
        return $this->toJson(self::SUCCESS);
    }

    //系统用户黑名单列表
    public function blackList(Request $request)
    {
        return $this->toJson(self::SUCCESS, $this->apiUserModel->blackList($request));
    }

    //解除系统用户黑名单
    public function blackListDelete(Request $request)
    {
        $res = $this->apiUserModel->blackListDelete($request->all());
        if ($res['code'] != self::SUCCESS) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::USER, '解除系统用户黑名单');
        return $this->toJson(self::SUCCESS);
    }

    //新增系统用户黑名单
    public function blackListAdd(Request $request)
    {
        $res = $this->apiUserModel->blackListAdd($request->all());
        if ($res['code'] != self::SUCCESS) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::USER, '新增系统用户黑名单');
        return $this->toJson(self::SUCCESS);
    }




}
